﻿/**
 * Author:
 *				Đỗ Việt Hoà
 * Copyright (c) 2012 Đỗ Việt Hoà <vit@launchar.com>.
 * 
 * This file is part of Launchar.
 * 
 * Launchar is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Launchar is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Launchar.  If not, see <http://www.gnu.org/licenses/>.
 */

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using vIT.Web.Configuration;

namespace vIT.Web.Security
{
	/// <summary>
	/// Membership provider.
	/// </summary>
	public abstract class MembershipProvider
	{
		#region Gets provider

		private static Dictionary<string, MembershipProvider> __providers = null;

		/// <summary>
		/// Returns the <see cref="vIT.Web.Security.MembershipProvider"/> object that contains the membership provider with the provider name.
		/// </summary>
		/// <param name="name">The provider name.</param>
		public static MembershipProvider GetProvider(string name)
		{
			if (__providers == null)
			{
				//
				// Initializes all providers.
				__providers = new Dictionary<string, MembershipProvider>();
				var config = WebConfig.Membership;

				foreach (var cfg in config.Providers)
				{
					MembershipProvider provider = null;
					try { provider = (MembershipProvider)Type.GetType(cfg.TypeName).GetConstructor(new Type[] { }).Invoke(new object[] { }); }
					catch { continue; }
					provider.Initialize(cfg.Config);
					__providers.Add(cfg.ProviderName, provider);
				}
			}

			return __providers[name];
		}

		#endregion

		#region Abstract methods

		/// <summary>
		/// Initializes the provider with the configuration.
		/// </summary>
		/// <param name="config">The configuration.</param>
		protected abstract void Initialize(NameValueCollection config);

		/// <summary>
		/// Validates user with the username and password.
		/// </summary>
		/// <param name="name">The username.</param>
		/// <param name="password">The password.</param>
		public abstract User ValidateUser(string name, string password);

		#endregion
	}
}
